<?php
/**
 * redis 缓存 根据 hash 模式自动分配对应的数据库
 *  当不设置key时候默认操作第一个数据库
 * Created by lni_wang.
 * Product: PhpStorm
 * Date: 2017/4/6 15:00
 * File: Redis_hash.php
 */
class Redis_hash
{
    private $_link = null;
    private $_sever_number = 1;

    function __construct($active_group = 'default')
    {
        $CI =& get_instance();
        $this->config        = $CI->config->item('redis');
        $this->_sever_number = count($this->config);
    }

    //把字符串K转换为 0～m-1 之间的一个值作为对应记录的散列地址
    function _hashId($id)
    {
        $k = md5($id);
        $l = strlen($k);
        $b = bin2hex($k);
        $h = 0;
        for ($i = 0; $i < $l; $i++){
            //相加模式HASH
            $h += substr($b, $i * 2, 2);
        }
        $hash = ($h * 1) % $this->_sever_number;
        return $hash;
    }

    public function redis($key = null)
    {
        if(!empty($key)){
            $_id = $this->_hashId($key);
        }else{
            $_id = 0;
        }

        if(!isset($this->_link[$_id])){
            $this->_link[$_id] = new Redis();
            $this->_link[$_id]->pconnect($this->config[$_id]['host'], $this->config[$_id]['port']);
            $this->_link[$_id]->select($this->config[$_id]['database']);
        }else{
            $this->_link[$_id]->ping();
        }
        return $this->_link[$_id];
    }

    public function close_all_link(){
        for($i=0; $i < $this->_sever_number; $i++){
            if(isset($this->_link[$i])){
                $this->_link[$i]->close();
            }
        }
        $this->_link = null;
    }
}